package com.sunny.design.proxy.staticproxy.exam2;

import com.sunny.design.proxy.IOrderService;
import com.sunny.design.proxy.Order;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 静态代理类
 *  动态根据订单创建年份分库存数据
 *
 * @author Sunny
 * @date 2020/1/1 17:04
 */
public class OrderServiceStaticProxy implements IOrderService {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy");

    private IOrderService orderService;
    public OrderServiceStaticProxy(IOrderService orderService){
        this.orderService = orderService;
    }

    @Override
    public int createOrder(Order order) {
        before();
        Long createTime = order.getCreateTime();
        int dbRouter = Integer.parseInt(format.format(new Date(createTime)));
        System.out.println("静态代理类自动分配到【DB_" + dbRouter + "】数据源处理数据。");
        DynamicDataSourceEntry.set(dbRouter);
        orderService.createOrder(order);
        DynamicDataSourceEntry.restore();
        after();
        return 0;
    }

    public void before() {
        System.out.println("Proxy before method");
    }

    public void after() {
        System.out.println("Proxy after method");
    }
}
